// 学习目标管理云函数
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const goalsCollection = db.collection('goals')

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const openid = wxContext.OPENID
  const { action, goalData } = event
  
  if (!openid) {
    return {
      code: -1,
      msg: '获取用户openid失败',
      data: null
    }
  }
  
  try {
    switch (action) {
      case 'add':
        return await addGoal(openid, goalData)
      case 'update':
        return await updateGoal(openid, goalData)
      case 'get':
        return await getGoal(openid)
      case 'delete':
        return await deleteGoal(openid, goalData.goalId)
      case 'clear':
        return await clearAllGoals(openid)
      default:
        return {
          code: -1,
          msg: '无效的操作类型',
          data: null
        }
    }
  } catch (err) {
    console.error('学习目标管理失败:', err)
    return {
      code: -1,
      msg: '操作失败',
      error: err
    }
  }
}

// 添加学习目标
async function addGoal(openid, goalData) {
  const { title, deadline } = goalData
  
  if (!title || !deadline) {
    return {
      code: -1,
      msg: '学习目标和完成时间不能为空',
      data: null
    }
  }
  
  // 检查用户是否已有学习目标
  const existingGoal = await goalsCollection.where({
    openid: openid,
    status: 'active'
  }).get()
  
  if (existingGoal.data.length > 0) {
    return {
      code: -1,
      msg: '您已有活跃的学习目标，请先完成或修改现有目标',
      data: null
    }
  }
  
  const result = await goalsCollection.add({
    data: {
      openid: openid,
      title: title,
      deadline: deadline,
      status: 'active',
      progress: 0,
      createTime: db.serverDate(),
      updateTime: db.serverDate()
    }
  })
  
  return {
    code: 0,
    msg: '学习目标添加成功',
    data: {
      goalId: result._id,
      title: title,
      deadline: deadline,
      status: 'active',
      progress: 0
    }
  }
}

// 更新学习目标
async function updateGoal(openid, goalData) {
  const { goalId, title, deadline } = goalData
  
  if (!goalId) {
    return {
      code: -1,
      msg: '目标ID不能为空',
      data: null
    }
  }
  
  if (!title || !deadline) {
    return {
      code: -1,
      msg: '学习目标和完成时间不能为空',
      data: null
    }
  }
  
  const result = await goalsCollection.doc(goalId).update({
    data: {
      title: title,
      deadline: deadline,
      updateTime: db.serverDate()
    }
  })
  
  if (result.stats.updated === 0) {
    return {
      code: -1,
      msg: '目标不存在或无权限修改',
      data: null
    }
  }
  
  return {
    code: 0,
    msg: '学习目标修改成功',
    data: {
      goalId: goalId,
      title: title,
      deadline: deadline
    }
  }
}

// 获取学习目标
async function getGoal(openid) {
  const result = await goalsCollection.where({
    openid: openid,
    status: 'active'
  }).orderBy('createTime', 'desc').limit(1).get()
  
  return {
    code: 0,
    msg: '获取成功',
    data: result.data.length > 0 ? result.data[0] : null
  }
}

// 删除学习目标
async function deleteGoal(openid, goalId) {
  if (!goalId) {
    return {
      code: -1,
      msg: '目标ID不能为空',
      data: null
    }
  }
  
  const result = await goalsCollection.doc(goalId).update({
    data: {
      status: 'deleted',
      updateTime: db.serverDate()
    }
  })
  
  if (result.stats.updated === 0) {
    return {
      code: -1,
      msg: '目标不存在或无权限删除',
      data: null
    }
  }
  
  return {
    code: 0,
    msg: '学习目标删除成功',
    data: null
  }
}

// 清空所有学习目标
async function clearAllGoals(openid) {
  // 获取用户所有活跃的学习目标
  const existingGoals = await goalsCollection.where({
    openid: openid,
    status: 'active'
  }).get()
  
  if (existingGoals.data.length === 0) {
    return {
      code: 0,
      msg: '没有需要清空的学习目标',
      data: null
    }
  }
  
  // 批量更新所有目标状态为已删除（逐条更新，CloudBase 无 db.batch）
  await Promise.all(
    existingGoals.data.map(goal =>
      goalsCollection.doc(goal._id).update({
        data: {
          status: 'deleted',
          updateTime: db.serverDate()
        }
      })
    )
  )
  
  return {
    code: 0,
    msg: `已清空 ${existingGoals.data.length} 个学习目标`,
    data: {
      clearedCount: existingGoals.data.length
    }
  }
}
